//
//  CNImageView.swift
//  Voice
//
//  Created by 卢逢卫 on 2024/3/13.
//

import UIKit

extension UIImageView {

    public static func cn_initWith(background: UIColor = UIColor.clear, named: String) -> UIImageView {
        let imageView = UIImageView(image: UIImage(named: named))
        imageView.backgroundColor = background
        return imageView
    }

    public func cn_download(from url: String, contentMode: UIView.ContentMode = .scaleAspectFit, placeholder: UIImage? = nil, completionHandler: ((UIImage?) -> Void)? = nil) {
        self.contentMode = contentMode
        self.image = placeholder

        guard let url = URL(string: url) else {
            completionHandler?(nil)
            return
        }

        let session = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
            guard let data = data, error == nil else {
                completionHandler?(nil)
                return
            }

            DispatchQueue.main.async {
                let downloadedImage = UIImage(data: data)
                self?.image = downloadedImage
                completionHandler?(downloadedImage)
            }
        }
        session.resume()
    }
}
